//
//  AppDelegate+AppService.m
//  Bees
//
//  Created by xiaohan on 2017/5/19.
//  Copyright © 2017年 xiaohan. All rights reserved.
//

#import "AppDelegate+AppService.h"
#import "JJFontFit.h"
#import "IQKeyboardManager.h"
#import "LoginViewController.h"
#import "AppDelegate+NTESService.h"
#import "MineServer.h"
#import <Bugly/Bugly.h>
#import <AvoidCrash/AvoidCrash.h>

//#import "LMJIntroductoryPagesView.h"
//#import <UMPush/UMessage.h>
//#import "UIColor+GradualChanging.h"
//#import "UpdateApp.h"
//#import "AdvertiseHelper.h"
//#import "ActivityViewController.h"

@implementation AppDelegate (AppService)


#pragma mark ————— 初始化服务 —————
-(void)initService{
    //注册登录状态监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginStateChange:)
                                                 name:KNotificationLoginStateChange
                                               object:nil];    
    
    //网络状态监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(netWorkStateChange:)
                                                 name:KNotificationNetWorkStateChange
                                               object:nil];
    ///异常抓取
    [AvoidCrash becomeEffective];
    [Bugly startWithAppId:kBuglyKey];
}

#pragma mark ————— 初始化window —————
-(void)initWindow{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    if (@available(iOS 11.0, *)){
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    ///多语言设置
    [XLocalzableTool initLocalized];
    [self checkUpdate];
    [self setupCustom];
}
- (void)checkUpdate{
    MineServer*mineServer = [MineServer new];
    [mineServer getUpgradeVer:CurrentAppVersion ompletion:^(BOOL success, NSString * _Nonnull msg) {
        if (success) {
            if (mineServer.updateM) {
                [XAlertTool alertTitle:msg message:[mineServer.updateM.update_content componentsJoinedByString:@"\n"] cancelAction:mineServer.updateM.force_update?nil:^{
                    
                } sureAction:^{
                    if (@available(iOS 10.0, *)) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mineServer.updateM.download_url] options:@{} completionHandler:nil];
                    } else {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mineServer.updateM.download_url]];
                    }
                }];
            }
        }
    }];
    ///检查更新
//    [[UpdateApp sharedManager] updateWithAPPID:nil withBundleId:nil block:^(NSString *currentVersion, NSString *storeVersion, NSString *openUrl, BOOL isUpdate,BOOL mustUpdate, NSString *updateContent) {
//        if (isUpdate) {
//            UpDataView *_upDataView = [[UpDataView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) andNewVer:storeVersion andLowVer:currentVersion andSize:@"" andContent:updateContent];
//            _upDataView.urlStr = openUrl;
//            _upDataView.update = mustUpdate;
//            [_upDataView appear];
//        }else{
//
//        }
//    }];
}

- (void)startAD{
//    return;
    ///广告页
//    if ([kUserManager loadUserInfo]) {
//    [AdvertiseHelper showAdvertiserView:nil AdClick:^{
//        UIViewController*currentVC = [kAppDelegate getCurrentVC];
//        NSDictionary*data = VALUEFORKEY(adData);
//        if (!data) {
//            return;
//        }
//        NSInteger jump_type = [data[@"jump_type"] integerValue];
//        switch (jump_type) {
//            case 1:
//            {///内部跳转
//                Class Cls = NSClassFromString(data[@"ios_go"]);
//                if (Cls) {
//                    RootViewController*vc = [Cls new];
//                    [currentVC.navigationController pushViewController:vc animated:YES];
//                }
//
//            }
//                break;
//            case 2:
//            {///webView跳转
//                ToObtainWebViewController *vc = [ToObtainWebViewController new];
//                vc.gotoURL = data[@"redirect_url"];
//                vc.titleStr = data[@"name"];
//                [currentVC.navigationController pushViewController:vc animated:YES];
//            }
//                break;
//            case 3:
//            {///弹窗
//                [ActivityViewController showPromptInVC:currentVC infoImg:data[@"image"] infoStr:data[@"dialog"] closeBlock:^(BOOL close) {
//
//                }];
//            }
//                break;
//            default:
//                break;
//        }
//    }];

//    }
}

//自定义样式
- (void)setupCustom{
    if (kScreenWidth == 320) {//4.0寸手机
        //在原来字体的大小上-2
        [JJFontFit fontFitWithAddSize:-2];
    }else{
        [JJFontFit fontFitWithAddSize:0];
    }
//    [JJFontFit fontFitWithAddSize:kScreenWidthRatio];
    //    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [[UITextField appearance] setTintColor:kColorMain];
    [[UITextView appearance] setTintColor:kColorMain];
    [UITextField appearance].clearButtonMode = UITextFieldViewModeWhileEditing;
    [[UIButton appearance] setExclusiveTouch:YES];
    [CSToastManager sharedStyle].displayShadow = YES;
    [CSToastManager sharedStyle].shadowOffset = CGSizeMake(0, 0);
    [CSToastManager setDefaultDuration:2.];
    [CSToastManager setDefaultPosition:CSToastPositionCenter];

//    [CSToastManager sharedStyle].backgroundColor = kColorMain;
//    [CSToastManager sharedStyle].shadowColor = kColorMain;
//    [CSToastManager sharedStyle].messageColor = kTitleColor;
}
#pragma mark ————— 初始化用户系统 —————
-(void)initUserManager{

//    kWeakSelf(self);
    //如果有本地数据，先展示TabBar 随后异步自动登录
    self.mainTabBar = [MainTabBarViewController new];
    self.window.rootViewController = self.mainTabBar;
    if([kUserManager loadUserInfo]){
        [self autoLogin];
//        [[[NIMSDK sharedSDK]loginManager]login:kCurUser.im_account token:kCurUser.im_token completion:^(NSError * _Nullable error) {
//            if (!error) {
//                DLog(@"聊天登录账号%@",[[[NIMSDK sharedSDK]loginManager] currentAccount]);
//            }else{
//                DLog(@"聊天登录失败%@",error.description);
//            }
//        }];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self checkUpdate];
//        });
        //获取用户信息
//        [kUserManager autoGetUserInformation:^(BOOL success, NSInteger code, NSString *des) {
//            if (success) {
//                KPostNotification(KNotificationAutoLoginSuccess, nil);
//            }else{
//                [MBProgressHUD showWarn:@"账号出现异常,请重新登录" ToView:[kAppDelegate getCurrentVC].view];
//                KPostNotification(KNotificationLoginStateChange, @NO)
//            }
//        }];
//        [kUserManager autoLoginToServer:^(BOOL success,NSInteger code, NSString *des) {
//            if (success) {
//                DLog(@"自动登录成功");
//                KPostNotification(KNotificationAutoLoginSuccess, nil);
//                KPostNotification(KNotificationLoginStateChange, @YES)
//            }
//        }];

    }else{
        //没有登录过，展示登录页面
//        KPostNotification(KNotificationLoginStateChange, @NO)
    }
    
    // 欢迎视图
//    [LMJIntroductoryPagesView showIntroductoryPageView:@[@"intro_0", @"intro_1", @"intro_2", @"intro_3"]];
}

- (void)logout{
//    [kUserManager logout:^(BOOL s, NSString *des) {
//
//    }];
}


#pragma mark ————— 登录状态处理 —————
- (void)loginStateChange:(NSNotification *)notification
{
    BOOL loginSuccess = [notification.object boolValue];
    
    if (loginSuccess) {
 
    }else {
      
    }
}


#pragma mark ————— 网络状态变化 —————
- (void)netWorkStateChange:(NSNotification *)notification
{
//    BOOL isNetWork = [notification.object boolValue];
//    if (isNetWork) {//有网络
//        if ([kUserManager loadUserInfo] && !kIsLogin) {//有用户数据 并且 未登录成功 重新来一次自动登录
//            [kUserManager autoLoginToServer:^(BOOL success,NSInteger code, NSString *des) {
//                if (success) {
//                    DLog(@"网络改变后，自动登录成功");
//                    KPostNotification(KNotificationAutoLoginSuccess, nil);
//                }else{
//                    KPostNotification(KNotificationLoginStateChange, @NO);
//                }
//            }];
//        }
//
//    }else {//登陆失败加载登陆页面控制器
//        [MBProgressHUD showTopTipMessage:@"网络状态不佳" isWindow:YES];
//    }
}


#pragma mark ————— 友盟 初始化 —————
-(void)initUMeng{
    /* 打开调试日志 */
//    [[UMSocialManager defaultManager] openLog:YES];
    
    /* 设置友盟appkey */
//    [[UMSocialManager defaultManager] setUmSocialAppkey:UMengKey];
    
    [self configUSharePlatforms];
}
#pragma mark ————— 配置第三方 —————
-(void)configUSharePlatforms{
    /* 设置微信的appKey和appSecret */
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:kAppKey_Wechat appSecret:kSecret_Wechat redirectURL:nil];
    /*
     * 移除相应平台的分享，如微信收藏
     */
    //[[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:kAppKey_Tencent/*设置QQ平台的appID*/  appSecret:nil redirectURL:nil];
}

#pragma mark ————— 网络状态监听 —————
- (void)monitorNetworkStatus
{
    // 网络状态改变一次, networkStatusWithBlock就会响应一次
    [PPNetworkHelper networkStatusWithBlock:^(PPNetworkStatusType networkStatus) {

        switch (networkStatus) {
                // 未知网络
            case PPNetworkStatusUnknown:
                DLog(@"网络环境：未知网络");
                // 无网络
            case PPNetworkStatusNotReachable:
                DLog(@"网络环境：无网络");
                KPostNotification(KNotificationNetWorkStateChange, @NO);
                break;
                // 手机网络
            case PPNetworkStatusReachableViaWWAN:
                DLog(@"网络环境：手机自带网络");
                // 无线网络
            case PPNetworkStatusReachableViaWiFi:
                DLog(@"网络环境：WiFi");
                KPostNotification(KNotificationNetWorkStateChange, @YES);
                break;
        }

    }];
    
}

+ (AppDelegate *)shareAppDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

-(UIViewController *)getCurrentVC{
    
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    if (!window) {
        return nil;
    }
    UIView *tempView;
    for (UIView *subview in window.subviews) {
        if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) {
            tempView = subview;
            break;
        }
    }
    if (!tempView) {
        tempView = [window.subviews lastObject];
    }
    
    id nextResponder = [tempView nextResponder];
    while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) {
        tempView =  [tempView.subviews firstObject];
        
        if (!tempView) {
            return nil;
        }
        nextResponder = [tempView nextResponder];
    }
    return  (UIViewController *)nextResponder;
}

@end
